package com.lambda.hybrid;

import android.content.Context;
import android.content.res.Resources;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

public class HybridToolbar implements View.OnClickListener {
    private final HybridView mHybridView;
    private final View mToolbar;

    private TextView mTitleView;

    private ToolbarItem mBackItem;
    private ToolbarItem mCloseItem;

    public HybridToolbar(HybridView hybridView, View toolbar) {
        mHybridView = hybridView;
        mToolbar = toolbar;

        mTitleView = mToolbar.findViewById(R.id.hybrid_title);

        mBackItem = mToolbar.findViewById(R.id.nav_back);
        mBackItem.setOnClickListener(this);
        mCloseItem = mToolbar.findViewById(R.id.nav_close);
        mCloseItem.setOnClickListener(this);
    }

    public void setTitle(String title) {
        if (mTitleView != null) mTitleView.setText(title);
    }

    public void setTitleColor(int color) {
        if (mTitleView != null) mTitleView.setTextColor(color);
    }

    public void setVisible(boolean visible) {
        mToolbar.setVisibility(visible ? View.GONE : View.VISIBLE);
    }

    public void setBackgroundColor(int color) {
        mToolbar.setBackgroundColor(color);
    }

    public void hideBackButton(boolean hide) {
        setItemHidden(mBackItem, hide);
    }

    public void setBackButtonTitle(String text) {
        setItemText(mBackItem, text);
    }

    public void setBackButtonImage(String res) {
        setItemImage(mBackItem, res);
    }

    public void hideCloseButton(boolean hide) {
        setItemHidden(mCloseItem, hide);
    }

    public void setCloseButtonTitle(String text) {
        setItemText(mCloseItem, text);
    }

    public void setCloseButtonImage(String res) {
        setItemImage(mCloseItem, res);
    }

    private void setItemHidden(ToolbarItem item, boolean hide) {
        if (item != null) item.setVisibility(hide ? View.INVISIBLE : View.VISIBLE);
    }

    private void setItemText(ToolbarItem item, String text) {
        if (item != null) item.setText(text);
    }

    private void setItemImage(ToolbarItem item, String res) {
        if (item == null) return;

        Context context = item.getContext();

        if (!res.startsWith("http")) {
            Resources resources = item.getResources();
            int id = resources.getIdentifier(res, "drawable", context.getPackageName());
            if (id > 0) {
                item.setDrawable(ContextCompat.getDrawable(context, id));
            }
        }
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.nav_back) {
            if (mHybridView.canGoBack()) {
                mHybridView.goBack();
            } else {
                mHybridView.onClose();
            }
        } else if (vid == R.id.nav_close) {
            mHybridView.onClose();
        }
    }
}
